package com.zoweunion.mechanic.service.app.impl;

import com.alibaba.fastjson.JSON;
import com.zoweunion.mechanic.dao.app.AppDao;
import com.zoweunion.mechanic.dao.app.OrderDao;
import com.zoweunion.mechanic.dao.app.ToolCarDataMapper;
import com.zoweunion.mechanic.dao.app.ToolViewBoardMapper;
import com.zoweunion.mechanic.dao.order.CGOrderDao;
import com.zoweunion.mechanic.model.User;
import com.zoweunion.mechanic.model.app.AssignRegion;
import com.zoweunion.mechanic.model.app.ViewBoardMenu;
import com.zoweunion.mechanic.model.things.ThingsData;
import com.zoweunion.mechanic.service.app.AppService;
import com.zoweunion.mechanic.service.app.ToolViewBoardService;
import com.zoweunion.mechanic.service.base.BaseService;
import com.zoweunion.mechanic.service.base.impl.VehicleDataServiceImpl;
import com.zoweunion.mechanic.util.Orgin;
import com.zoweunion.mechanic.util.constants.Constants;
import com.zoweunion.mechanic.util.DateUtil;
import com.zoweunion.mechanic.util.HttpClient;
import com.zoweunion.mechanic.util.MyException;
import com.zoweunion.mechanic.util.gaode.AddressGEOUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhangjun
 */
@Service
public class ToolViewBoardServiceImpl extends BaseService implements ToolViewBoardService {

    @Autowired
    private AddressGEOUtil addressGEOUtil;

    @Autowired
    private ToolCarDataMapper toolCarDataMapper;
    @Autowired
    AppDao appDao;
    @Autowired
    AppService appService;
    @Autowired
    ToolViewBoardMapper toolViewBoardMapper;
    @Autowired
    OrderDao orderDao;
    @Autowired
    CGOrderDao cgOrderDao;
    @Autowired
    VehicleDataServiceImpl vehicleDataServiceImpl;

    @Override
    public Map<String, Object> todayStatistics(User currentUser) {
        // 获取当前用户的管辖区域
        String precinctRegions = null;
        if (!Constants.ROLE_GLY.equals(currentUser.getR_id())) {
            precinctRegions = String.join(",", appService.getPrecinctRegionNumbers(currentUser.getId(), currentUser.getS_id()));
        }
        Map<String, Object> orderMap = toolViewBoardMapper.todayStatistics(precinctRegions, currentUser.getS_id());
        if (orderMap == null) {
            orderMap = new HashMap<>(6);
            orderMap.put("todayReservation", 0);
            orderMap.put("todayComplete", 0);
            orderMap.put("todayGoWork", 0);
        }
        return orderMap;
    }

    @Override
    public List<Map<String, Object>> listOrderInfo(User currentUser, Map<String, Object> reqMap) {
        // 设置分页的limit和offset
        this.appPage(reqMap);
        // 获取当前用户的管辖区域
        setPrecinctRegionsInReqMap(currentUser, reqMap);
        reqMap.put("sId", currentUser.getS_id());
        List<Map<String, Object>> maps = toolViewBoardMapper.listOrderInfo(reqMap);
        return this.listByFault(maps,currentUser.getS_id());
    }

    @Override
    public List<Map<String, Object>> listByFault(List<Map<String, Object>> maps,String sId) {
        if (maps.size()!=0){
            maps.forEach(item->{

                if (item != null && item.get("parent_id") != null) {

                    String parent_id = item.get("parent_id").toString();
                    if (!parent_id.equals("0")){
                        Map<String, Object> map = cgOrderDao.selectDictionariesByInfo(parent_id, sId);
                        item.put("dictionaries_name",map.get("dictionaries_name"));
                    }
                }
            });
        }

        return maps;
    }

    @Override
    public List<Map<String, Object>> listRealTimeOrder(User currentUser, Map<String, Object> reqMap) {
        // 设置分页的limit和offset
        this.appPage(reqMap);
        // 获取当前用户的管辖区域
        setPrecinctRegionsInReqMap(currentUser, reqMap);
        reqMap.put("sId", currentUser.getS_id());
        List<Map<String, Object>> orderList = toolViewBoardMapper.listRealTimeOrder(reqMap);
        orderList.forEach(map -> map.putIfAbsent("waitTotalMinute", 0));
        return orderList;
    }

    @Override
    public List<ViewBoardMenu> listMenu(User user) {
        return toolViewBoardMapper.listViewBoardByRole(user.getR_id());
    }

    /**
     * 故障类型统计 饼图
     * 车主和服务商页面之间的区别，就在于是否传递oId,传参就是车主页面
     * @return
     */
    @Override
    public List<Map<String, Object>> pieFaultTypeStatistics(User currentUser, Map<String, Object> reqMap) {
        // 设置权限
        this.setPermission(currentUser, reqMap);
        // 获取当前用户的管辖区域
        setPrecinctRegionsInReqMap(currentUser, reqMap);
        if (Orgin.getString(reqMap, "precinctRegions").equals("没有分配区域")) {
            reqMap.put("precinctRegions", "");
        }
        reqMap.put("sId", currentUser.getS_id());
        //获取大故障类型
        List<Map<String, Object>> nameList = toolViewBoardMapper.ListDictionariesNameBySId(reqMap);
        //获取对应工单各故障类型数量
        List<Map<String, Object>> faultTypeList = toolViewBoardMapper.pieFaultTypeStatistics(reqMap);
        faultTypeList.forEach(item->{
            String id = item.get("id").toString();
            //计算各故障类型的工单数量
            Integer integer = toolViewBoardMapper.selectFaultCount(id, currentUser.getS_id(), Orgin.getString(reqMap, "oId"));
            item.put("value",Integer.valueOf(item.get("value").toString())+integer);
        });
        List<String> keyList = faultTypeList.stream().map(orderTypeMap -> orderTypeMap.get("name").toString()).collect(Collectors.toList());
        String keyStr = String.join(",", keyList);
        for (Map<String, Object> nameMap : nameList) {
            if (!keyStr.contains(nameMap.get("name").toString())) {
                Map<String, Object> faultTypeMap = new HashMap<>(5);
                faultTypeMap.put("name", nameMap.get("name").toString());
                faultTypeMap.put("value", 0);
                faultTypeList.add(faultTypeMap);
            }
        }
        return faultTypeList;
    }

    /**
     * 工单类型统计 饼图
     * 车主和服务商页面之间的区别，就在于是否传递oId,传参就是车主页面
     * @return
     */
    @Override
    public List<Map<String, Object>> pieOrderTypeStatistics(User currentUser, Map<String, Object> reqMap) {
        // 设置权限
        this.setPermission(currentUser, reqMap);
        // 获取当前用户的管辖区域
        setPrecinctRegionsInReqMap(currentUser, reqMap);
        if (Orgin.getString(reqMap, "precinctRegions").equals("没有分配区域")) {
            reqMap.put("precinctRegions", "");
        }
        reqMap.put("sId", currentUser.getS_id());
        //区别车主和服务商之间的区别，就在于车主页面多传递oId参数
      List<Map<String, Object>> orderTypeMapList = toolViewBoardMapper.pieOrderTypeStatistics(reqMap);
        List<String> keyList = orderTypeMapList.stream().map(orderTypeMap -> orderTypeMap.get("name").toString()).collect(Collectors.toList());
        if (!keyList.contains("维修工单")) {
            Map<String, Object> wxMap = new HashMap<>(5);
            wxMap.put("name", "维修工单");
            wxMap.put("value", 0);
            orderTypeMapList.add(wxMap);
        }
        if (!keyList.contains("保养工单")) {
            Map<String, Object> wxMap = new HashMap<>(5);
            wxMap.put("name", "保养工单");
            wxMap.put("value", 0);
            orderTypeMapList.add(wxMap);
        }
        if (!keyList.contains("维修+保养工单")) {
            Map<String, Object> wxMap = new HashMap<>(5);
            wxMap.put("name", "维修+保养工单");
            wxMap.put("value", 0);
            orderTypeMapList.add(wxMap);
        }
        return orderTypeMapList;
    }

    @Override
    public Map<String, Object> getOrderStatisticsData(User currentUser, Map<String, Object> reqMap) {
        // 设置权限
        this.setPermission(currentUser, reqMap);
        // 获取当前用户的管辖区域
        setPrecinctRegionsInReqMap(currentUser, reqMap);
        reqMap.put("sId", currentUser.getS_id());
        Map<String, Object> orderMap = toolViewBoardMapper.getOrderStatisticsData(reqMap);
        if (orderMap == null) {
            orderMap = new HashMap<>(6);
            orderMap.put("reservationNum", 0);
            orderMap.put("completionNum", 0);
            orderMap.put("totalNum", 0);
        }
        return orderMap;
    }

    private void setPermission(User currentUser, Map<String, Object> reqMap){
        String roleId = currentUser.getR_id();
        reqMap.put("currentRoleId", currentUser.getR_id());
        reqMap.put("currentUserId", currentUser.getId());
        if (Constants.ROLE_KF.equals(roleId)) {
            reqMap.put("currentRole", "KF");
        } else if (Constants.ROLE_TZ.equals(roleId)) {
            reqMap.put("currentRole", "TZ");
        } else if (Constants.ROLE_XG.equals(roleId)) {
            reqMap.put("currentRole", "XG");
        } else if (Constants.ROLE_CG.equals(roleId)) {
            reqMap.put("currentRole", "CG");
        } else if (Constants.ROLE_CZ.equals(roleId)) {
            reqMap.put("currentRole", "CZ");
        } else if (Constants.ROLE_SJ.equals(roleId)) {
            reqMap.put("currentRole", "SJ");
        } else if (Constants.ROLE_GLY.equals(roleId)) {
            reqMap.put("currentRole", "GLY");
        } else if (Constants.ROLE_GG.equals(roleId)) {
            reqMap.put("currentRole", "GG");
        } else if (Constants.ROLE_YK.equals(roleId)) {
            reqMap.put("currentRole", "YK");
        }
    }

    @Override
    public Map<String, Object> orderStatisticsHistogram(User currentUser, Map<String, Object> reqMap) {
        // 设置权限
        this.setPermission(currentUser, reqMap);
        // 设置管辖区域
        setPrecinctRegionsInReqMap(currentUser, reqMap);
        reqMap.put("sId", currentUser.getS_id());
        // 设置钻取的区域
        this.setDrillAreaInReqMap(reqMap);
        List<Map<String, Object>> orderStatisticsMap = toolViewBoardMapper.getOrderStatisticsHistogram(reqMap);
        if (orderStatisticsMap.size() == 1) {
            reqMap.put("region", "province");
            reqMap.put("regionName", orderStatisticsMap.get(0).get("regionName"));
            orderStatisticsMap = toolViewBoardMapper.getOrderStatisticsHistogram(reqMap);
            if (orderStatisticsMap.size() == 1) {
                reqMap.put("region", "city");
                reqMap.put("regionName", orderStatisticsMap.get(0).get("regionName"));
                orderStatisticsMap = toolViewBoardMapper.getOrderStatisticsHistogram(reqMap);
            }
        }
        reqMap.put("count", true);
        List<Map<String, Object>> countMap = toolViewBoardMapper.getOrderStatisticsHistogram(reqMap);
        Map<String, Object> resultMap = new HashMap<>(4);
        resultMap.put("list", orderStatisticsMap);
        resultMap.put("orderTotal", countMap.get(0).get("orderTotal"));
        return resultMap;
    }

    @Override
    public Map<String, Object> getRepairOrderStatistics(User currentUser, Map<String, Object> reqMap) {
        // 设置权限
        this.setPermission(currentUser, reqMap);
        // userId不为null是查询修工，
        if (reqMap.get("userId") == null) {
            // 设置管辖区域
            setPrecinctRegionsInReqMap(currentUser, reqMap);
        }
        reqMap.put("sId", currentUser.getS_id());
        Map<String, Object> repairOrderMap = toolViewBoardMapper.getRepairOrderStatistics(reqMap);
        if (repairOrderMap == null) {
            repairOrderMap = new HashMap<>(6);
            repairOrderMap.put("completeTotalNum", 0);
            repairOrderMap.put("backRatio", 0);
            repairOrderMap.put("avgRepairTime", 0);
        }
        return repairOrderMap;
    }

    @Override
    public Map<String, Object> listMaintainRepairAbility(User currentUser, Map<String, Object> reqMap) {
        Map<String, Object> resultMap = new HashMap<>();
        this.appPage(reqMap);
        // 当前用户的管辖区域
        setPrecinctRegionsInReqMap(currentUser, reqMap);
        reqMap.put("sId", currentUser.getS_id());
        resultMap.put("list", toolViewBoardMapper.listMaintainRepairAbility(reqMap));
        resultMap.put("r_id", currentUser.getR_id());
        return resultMap;
    }

    @Override
    public List<Map<String, Object>> listOrderWarningCreditAmount(User currentUser, Map<String, Object> reqMap) {
        // 设置分页的limit和offset
        this.appPage(reqMap);
        // 当前用户的管辖区域
        setPrecinctRegionsInReqMap(currentUser, reqMap);
        reqMap.put("sId", currentUser.getS_id());
        reqMap.put("warningLimit", 0.2);
        return toolViewBoardMapper.listOrderWarningCreditAmount(reqMap);
    }

    @Override
    public Map<String, Object> getPaymentStatistics(User currentUser, Map<String, Object> reqMap) {
        // 当前用户的管辖区域
        setPrecinctRegionsInReqMap(currentUser, reqMap);
        reqMap.put("sId", currentUser.getS_id());
        Map<String, Object> paymentMap = toolViewBoardMapper.getPaymentStatistics(reqMap);
        if (paymentMap == null) {
            paymentMap = new HashMap<>(6);
            paymentMap.put("todayIncome", "0.00");
            paymentMap.put("totalIncome", "0.00");
            paymentMap.put("waitPayback", "0.00");
        }
        return paymentMap;
    }

    @Override
    public List<Map<String, Object>> getRevenueStatistics(User currentUser, Map<String, Object> reqMap) throws MyException {
        final String day = "day", year = "year";
        // 当前用户的管辖区域
        setPrecinctRegionsInReqMap(currentUser, reqMap);
        reqMap.put("sId", currentUser.getS_id());

        LocalDate dateS = LocalDate.parse(reqMap.get("dateS").toString(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate dateE = LocalDate.parse(reqMap.get("dateE").toString(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        if (dateS.isAfter(dateE)) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "开始日期必须小于结束日期");
        }
        int totalMonths = DateUtil.getMonths(dateS, dateE);
        String type = totalMonths > 2 ? year : day;
        reqMap.put("type", type);
        List<Map<String, Object>> revenueList = toolViewBoardMapper.getRevenueStatistics(reqMap);
        // 对于横坐标日期的填充
        long totalDays = ChronoUnit.DAYS.between(dateS, dateE);
        List<Map<String, Object>> revenueCopyList = new ArrayList<>(revenueList);
        int revenueListSize = revenueCopyList.size() - 1;
        if (day.equals(type)) {
            for (int i = 0; i <= totalDays; i++) {
                if (revenueCopyList.size() > 0) {
                    for (Map<String, Object> revenueCopyMap : revenueCopyList) {
                        LocalDate revenueDate = LocalDate.parse(revenueCopyMap.get("date").toString(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                        if (dateS.plusDays(i).equals(revenueDate)) {
                            break;
                        }
                        if (revenueCopyMap.equals(revenueCopyList.get(revenueListSize))) {
                            revenueList.add(this.createRevenueMap(dateS, i, "yyyy-MM-dd", type));
                        }
                    }
                } else {
                    revenueList.add(this.createRevenueMap(dateS, i, "yyyy-MM-dd", type));
                }
            }
        } else {
            for (int i = 0; i <= totalMonths; i++) {
                if (revenueCopyList.size() > 0) {
                    for (Map<String, Object> revenueCopyMap : revenueCopyList) {
                        LocalDate revenueDate = LocalDate.parse(revenueCopyMap.get("date").toString() + "-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                        if (dateS.plusMonths(i).equals(revenueDate)) {
                            break;
                        }
                        if (revenueCopyMap.equals(revenueCopyList.get(revenueListSize))) {
                            revenueList.add(this.createRevenueMap(dateS, i, "yyyy-MM", type));
                        }
                    }
                } else {
                    revenueList.add(this.createRevenueMap(dateS, i, "yyyy-MM", type));
                }
            }
        }
        // 排序
        revenueList.sort((o1, o2) -> {
            String date = o1.get("date").toString();
            if (date.length() < 10) {
                return LocalDate.parse(o1.get("date").toString() + "-01").isBefore(LocalDate.parse(o2.get("date").toString() + "-01")) ? 1 : -1;
            }
            return LocalDate.parse(o1.get("date").toString()).isBefore(LocalDate.parse(o2.get("date").toString())) ?  -1 : 1;
        });
        return revenueList;
    }

    private Map<String, Object> createRevenueMap(LocalDate dateS, int i, String dateFormat, String type){
        Map<String, Object> revenueMap = new HashMap<>(3);
        if ("day".equals(type)) {
            revenueMap.put("date", dateS.plusDays(i).format(DateTimeFormatter.ofPattern(dateFormat)));
        } else if ("year".equals(type)){
            revenueMap.put("date", dateS.plusMonths(i).format(DateTimeFormatter.ofPattern(dateFormat)));
        }
        revenueMap.put("everyDayIncome", "0.00");
        return revenueMap;
    }

    /**
     * 营收统计-支付类型统计
     * 车主和服务商页面之间的区别，就在于是否传递oId,传参就是车主页面
     * @param reqMap
     * @return
     */
    @Override
    public List<Map<String, Object>> getPaymentTypeStatistics(User currentUser, Map<String, Object> reqMap) {
        // 获取当前用户的管辖区域
        setPrecinctRegionsInReqMap(currentUser, reqMap);
        if (Orgin.getString(reqMap, "precinctRegions").equals("没有分配区域")) {
            reqMap.put("precinctRegions", "");
        }
        reqMap.put("sId", currentUser.getS_id());
        List<Map<String, Object>> paymentTypeMapList = toolViewBoardMapper.getPaymentTypeStatistics(reqMap);
        List<String> keyList = paymentTypeMapList.stream().map(orderTypeMap -> orderTypeMap.get("name").toString()).collect(Collectors.toList());
        this.notExistAdd(paymentTypeMapList, keyList, "额度支付");
        this.notExistAdd(paymentTypeMapList, keyList, "微信支付");
        this.notExistAdd(paymentTypeMapList, keyList, "支付宝支付");
        this.notExistAdd(paymentTypeMapList, keyList, "现金支付");
        return paymentTypeMapList;
    }

    @Override
    public Map<String, Object> getCustomerStatistics(User currentUser, Map<String, Object> reqMap) {
        // 设置管辖区域
        setPrecinctRegionsInReqMap(currentUser, reqMap);
        reqMap.put("sId", currentUser.getS_id());
        Map<String, Object> customerMap = toolViewBoardMapper.getCustomerStatistics(reqMap);
        if (customerMap == null) {
            customerMap = new HashMap<>(6);
            customerMap.put("customerTotalNum", 0);
            customerMap.put("carTotalNum", 0);
            customerMap.put("activeValue", 100);
        }
        return customerMap;
    }

    @Override
    public Map<String, Object> getCustomerDistributedStatistics(User currentUser, Map<String, Object> reqMap) {
        Map<String, Object> resultMap = new HashMap<>();
        // 设置权限
        this.setPermission(currentUser, reqMap);
        // 设置管辖区域
        setPrecinctRegionsInReqMap(currentUser, reqMap);
        reqMap.put("sId", currentUser.getS_id());
        // 设置钻取的区域
        this.setDrillAreaInReqMap(reqMap);
        // 设置可向下钻取几次
        this.setDownClick(reqMap, resultMap);
        List<Map<String, Object>> orderStatisticsMap = toolViewBoardMapper.getCustomerDistributedStatistics(reqMap);

        if (orderStatisticsMap.size() == 1) {
            resultMap.put("downClick", 1);
            reqMap.put("region", "province");
            reqMap.put("regionName", orderStatisticsMap.get(0).get("regionName"));
            orderStatisticsMap = toolViewBoardMapper.getCustomerDistributedStatistics(reqMap);
            if (orderStatisticsMap.size() == 1) {
                resultMap.put("downClick", 0);
                reqMap.put("region", "city");
                reqMap.put("regionName", orderStatisticsMap.get(0).get("regionName"));
                orderStatisticsMap = toolViewBoardMapper.getCustomerDistributedStatistics(reqMap);
            }
        }
        resultMap.put("orderList", orderStatisticsMap);
        return resultMap;
    }

    private void setDownClick(Map<String, Object> reqMap, Map<String, Object> resultMap){
        String region = reqMap.get("region").toString();
        if ("default".equals(region)) {
            resultMap.put("downClick", 2);
        } else if ("province".equals(region)) {
            resultMap.put("downClick", 1);
        } else if ("city".equals(region)) {
            resultMap.put("downClick", 0);
        }
    }

    @Override
    public List<Map<String, Object>> listCustomerTotalOrder(User currentUser, Map<String, Object> reqMap) {
        this.appPage(reqMap);
        // 设置管辖区域
        setPrecinctRegionsInReqMap(currentUser, reqMap);
        reqMap.put("sId", currentUser.getS_id());
        List<Map<String, Object>> orderStatisticsMap = toolViewBoardMapper.listCustomerTotalOrder(reqMap);
        return orderStatisticsMap;
    }

    @Override
    public List<Map<String, Object>> listNeedMaintainCustomer(User currentUser, Map<String, Object> reqMap) {
        // 设置管辖区域
        this.appPage(reqMap);
        setPrecinctRegionsInReqMap(currentUser, reqMap);
        reqMap.put("sId", currentUser.getS_id());
        return toolViewBoardMapper.listNeedMaintainCustomer(reqMap);
    }

    @Override
    public Map<String, Object> getUserInfoByUserId(User currentUser, Map<String, Object> reqMap) {

        // 获取用户还款总额度
        Double orderRepaymentSum = 0.0;
        // 获取用户使用总额度
        Double orderUseSum = 0.0;
        // 可用额度
        Double useLimit = 0.0;

        Map<String, Object> resultMap = toolViewBoardMapper.getUserInfoByUserId(reqMap);

        if (orderDao.getOrderRepaymentSum(resultMap) != null) {

            orderRepaymentSum = Math.ceil(orderDao.getOrderRepaymentSum(resultMap));
        }

        if (orderDao.getOrderUseSum(resultMap) != null) {

            orderUseSum = Math.ceil(orderDao.getOrderUseSum(resultMap));
        }

        // 当前欠款
        Double nowDebt = orderUseSum - orderRepaymentSum;

        // 信用额度
        Double credit_limit = Math.ceil(Double.parseDouble(resultMap.get("creditLimit").toString()));

        // 欠款大于信用额度
        if (nowDebt < credit_limit) {

            // 当前可用总额度
            useLimit = credit_limit - nowDebt;
        }

        resultMap.put("useLimit",useLimit);

        return resultMap;
    }

    @Override
    public List<Map<String, Object>> listCarByUserId(User currentUser, Map<String, Object> reqMap) {
        this.appPage(reqMap);
        reqMap.put("runningDuration", 1000);
        reqMap.put("sId", currentUser.getS_id());
        List<Map<String, Object>> carInfoList = toolViewBoardMapper.listCarByUserId(reqMap);
        for (Map<String, Object> carInfo : carInfoList) {
            if (carInfo.get("address") == null || StringUtils.isBlank(carInfo.get("address").toString())) {
                //调用物联网卡地址接口查询信息
                String thingsInfo = HttpClient.doGet(Constants.THINGS_URL_ONE + carInfo.get("opcPath"), carInfo.get("interfaceAccount") + "", carInfo.get("unifyAccount") + "");
                // 获取该车辆实时地址
                List<Map<String, Object>> list;
                try {
                    list = JSON.parseObject(thingsInfo, List.class);
                } catch (Exception e) {
                    carInfo.put("address", "");
                    continue;
                }
                if (list != null && list.size() > 0) {
                    String address = list.get(0).get("NodeAddress").toString();
                    carInfo.put("address", list.get(0).get("NodeAddress"));
                    if (StringUtils.isBlank(address)) {
                        // 经度
                        String lon = list.get(0).get("Longitude").toString();
                        // 纬度
                        String lat = list.get(0).get("Latitude").toString();
                        if (!"0".equals(lon) && !"0".equals(lat)) {
                            Map<String, Object> geoInfoMap = addressGEOUtil.regeo(lon, lat);
                            if (geoInfoMap != null && geoInfoMap.get("regeocode") != null) {
                                Map<String, Object> regeocodeMap = (Map<String, Object>) geoInfoMap.get("regeocode");
                                if (regeocodeMap.get("formatted_address") != null) {
                                    carInfo.put("address", regeocodeMap.get("formatted_address"));
                                }
                            }
                        }
                    }
                }
            }
            if (StringUtils.isNotBlank(carInfo.get("address").toString())) {
                appDao.addCarAddress(carInfo);
            }
        }
        return carInfoList;
    }

    @Override
    public List<Map<String, Object>> listCarByUserIdNew(User currentUser, Map<String, Object> reqMap) throws MyException {
        this.appPage(reqMap);
        setPrecinctRegionsInReqMap(currentUser, reqMap);
        reqMap.put("runningDuration", 1000);
        reqMap.put("sId", currentUser.getS_id());
        List<Map<String, Object>> carInfoList = toolViewBoardMapper.listCarByUserIdNew(reqMap);
        for (Map<String, Object> carInfo : carInfoList) {
            carInfo.putIfAbsent("running", 0);
            carInfo.putIfAbsent("address", "");
            if (carInfo.get("thingsId") == null) {
                carInfo.putIfAbsent("address", "");
                continue;
            }
            String thingsId = carInfo.get("thingsId").toString();
            Map<String, Object> pcCarMap = toolCarDataMapper.getPcCar(thingsId);
            if (pcCarMap == null || pcCarMap.get("device_template") == null) {
                carInfo.putIfAbsent("address", "");
                continue;
            }
            String tableName = ThingsData.getTableName(pcCarMap.get("device_template").toString());
            // 获取车辆最新设备信息
            Map<String, Object> carDataMap = toolCarDataMapper.lastCarData(tableName, thingsId);
            if (carDataMap == null) {
                carInfo.putIfAbsent("address", "");
                continue;
            }
            String tableName2 = vehicleDataServiceImpl.selectTableByThingsIdByDate(thingsId, new Date());
            String EngineTotalHours = "0";
            // 运行时长
            if (null != tableName2 && tableName2.equals("")) {
                EngineTotalHours = toolCarDataMapper.getLargeEngineTotalHour(thingsId, tableName2 + "_tb1");
            }
            reqMap.put("running", EngineTotalHours);
            // 经度
            String lon = carDataMap.get("GPSlongitude").toString();
            // 纬度
            String lat = carDataMap.get("GPSlatitude").toString();
            if (!"0".equals(lon) && !"0".equals(lat)) {
                //存在0.0的情况，会导致下面方法的报错
                Map<String, Object> geoInfoMap = addressGEOUtil.regeo(lon, lat);
                if (geoInfoMap != null && geoInfoMap.get("regeocode") != null) {
                    Map<String, Object> regeocodeMap = (Map<String, Object>) geoInfoMap.get("regeocode");
                    if (regeocodeMap.get("formatted_address") != null) {
                        carInfo.put("address", regeocodeMap.get("formatted_address"));
                    }
                }
            }
            if (StringUtils.isNotBlank(carInfo.get("address").toString())) {
                appDao.addCarAddress(carInfo);
            }
        }
        return carInfoList;
    }

    /**
     * 设置钻取的区域
     *
     * @param reqMap
     */
    private void setDrillAreaInReqMap(Map<String, Object> reqMap) {
        if (reqMap.get("regionName") == null || StringUtils.isBlank(reqMap.get("regionName").toString())) {
            reqMap.put("region", "default");
        } else {
            String regionName = reqMap.get("regionName").toString();
            if (toolViewBoardMapper.hasProvinceName(regionName) > 0) {
                reqMap.put("region", "province");
            } else if (toolViewBoardMapper.hasCityName(regionName) > 0) {
                reqMap.put("region", "city");
            } else if (toolViewBoardMapper.hasAreaName(regionName) > 0) {
                reqMap.put("region", "area");
            }
        }
    }
    
    /**
     * 不存在时某个字段时，添加默认值
     *
     * @param mapList
     * @param keyList
     * @param name
     */
    private void notExistAdd(List<Map<String, Object>> mapList, List<String> keyList, String name) {
        if (!keyList.contains(name)) {
            Map<String, Object> wxMap = new HashMap<>(3);
            wxMap.put("name", name);
            wxMap.put("value", "0.00");
            mapList.add(wxMap);
        }
    }

    /**
     * app端看板获取管辖区域
     * @param currentUser
     * @param map
     * @return
     */
    @Override
    public Map<String, Object> getPrecinctRegionForApp(User currentUser, Map<String, Object> map) {
        String sId = currentUser.getS_id();
        List<AssignRegion> assignRegionList;
        // 如果当前角色是管理员则查找全部区域，否则查当前分配的区域
        if (Constants.ROLE_GLY.equals(currentUser.getR_id())) {
            assignRegionList = appDao.selectAssignRegionUserBySId(sId, null);
        } else {
            assignRegionList = appDao.selectAssignRegionUserBySId(sId, currentUser.getId());
        }
        // 定义数据对象map
        Map<String, Object> regionMap = new HashMap<>();
        Map<String, Object> provinceMap = new HashMap<>();
        Map<String, Object> cityMap = new HashMap<>();
        Map<String, Object> areaMap = new HashMap<>();
        // 封装数据到map对象中
        for (AssignRegion assignRegion : assignRegionList) {
            if (!provinceMap.containsKey(assignRegion.getProvinceNumber()) && StringUtils.isNotBlank(assignRegion.getProvinceNumber())) {
                provinceMap.put(assignRegion.getProvinceNumber(), assignRegion.getProvinceName());
            }
            if (!cityMap.containsKey(assignRegion.getCityNumber()) && StringUtils.isNotBlank(assignRegion.getCityNumber())) {
                cityMap.put(assignRegion.getCityNumber(), assignRegion.getCityName());
            }
            if (!areaMap.containsKey(assignRegion.getAreaNumber()) && StringUtils.isNotBlank(assignRegion.getAreaNumber())) {
                areaMap.put(assignRegion.getAreaNumber(), assignRegion.getAreaName());
            }
        }
        regionMap.put("province_list", provinceMap);
        regionMap.put("city_list", cityMap);
        regionMap.put("county_list", areaMap);
        return regionMap;
    }
}
